package com.zkca.xf.ui.activity.me;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.zkca.xf.Constants_SP;
import com.zkca.xf.R;
import com.zkca.xf.base.BaseTitleActivity;
import com.zkca.xf.model.javabean.upHead;
import com.zkca.xf.presenter.UpHeadPresenter;
import com.zkca.xf.utils.LogUtil;
import com.zkca.xf.utils.PopWindowUtil;
import com.zkca.xf.utils.SPUtil;
import com.zkca.xf.view.UpHeadView;


import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


//个人信息
public class PersonalDetailsActivity extends BaseTitleActivity implements UpHeadView, View.OnClickListener, TakePhoto.TakeResultListener, InvokeListener {


    private static final String TAG = TakePhotoActivity.class.getName();

    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_section)
    TextView tv_section;
    @BindView(R.id.tv_duty)
    TextView tv_duty;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.my_head)
    CircleImageView my_head;
    private LinearLayout ll_pd;
    View pop_head;


    private Map<String, String> map;
    private UpHeadPresenter upHeadPresenter;
    private TextView tv_photo_cancel, tv_photo_album, tv_photograph;

    private InvokeParam invokeParam;

    private Uri imageUri;//压缩后图片保存路径
    private TakePhoto takePhoto;
    private File file;
    private String userName,depName,orgName,mobile,userHead;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_details);
        ButterKnife.bind(this);
        setTitleText("个人信息");
        setleftTextVisibility(true);
        setleftImgVisibility(true);
        initView();
        initdata();
    }

    private void initView() {
        map = new HashMap();

        userName=SPUtil.getString(this,Constants_SP.USERNAME,"");
        depName=SPUtil.getString(this,Constants_SP.DEPTNAME,"");
        orgName=SPUtil.getString(this,Constants_SP.UNITNAME,"");
        mobile=SPUtil.getString(this,Constants_SP.ACCESSID,"");
        userHead=SPUtil.getString(this,Constants_SP.USER_HEAD,"");


        upHeadPresenter = new UpHeadPresenter(this, this);
        ll_pd = (LinearLayout) findViewById(R.id.ll_pd);
        pop_head = LayoutInflater.from(this).inflate(R.layout.pop_head, null, false);


        tv_photo_cancel = (TextView) pop_head.findViewById(R.id.tv_photo_cancel);
        tv_photo_album = (TextView) pop_head.findViewById(R.id.tv_photo_album);
        tv_photograph = (TextView) pop_head.findViewById(R.id.tv_photograph);
        tv_photo_cancel.setOnClickListener(this);
        tv_photo_album.setOnClickListener(this);
        tv_photograph.setOnClickListener(this);
    }

    private void initdata() {
        tv_name.setText(userName);//姓名
        tv_section.setText(depName);//部门
        tv_duty.setText(orgName);//单位
        tv_phone.setText(mobile);
        LogUtil.e("头像名", userHead+ "");
        Glide.with(PersonalDetailsActivity.this).load(R.mipmap.app_name).into(my_head);
    }

    @Override
    public void showProgressDialog() {

    }

    @Override
    public void hideProgressDialog() {

    }

    @Override
    public void showError(String msg) {
        LogUtil.e("000000", msg);
    }




    @OnClick(R.id.my_head)
    public void onClick(View view) {
        file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        imageUri = Uri.fromFile(file);
        takePhoto = getTakePhoto();
        configCompress(takePhoto);
        switch (view.getId()) {
            case R.id.my_head://头像
                PopWindowUtil.showPopWindow(PersonalDetailsActivity.this, pop_head, ll_pd);
                break;
            case R.id.tv_photo_cancel:
                PopWindowUtil.popupWindow.dismiss();
                break;
            case R.id.tv_photo_album://从相册

                PopWindowUtil.popupWindow.dismiss();

                takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions());
                break;
            case R.id.tv_photograph://拍照

                PopWindowUtil.popupWindow.dismiss();

                takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
                break;
        }
    }


    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    /**
     * 压缩
     *
     * @param takePhoto
     */
    private void configCompress(TakePhoto takePhoto) {
        CompressConfig config;
        config = new CompressConfig.Builder()
                .setMaxSize(102400)//压缩到的最大大小，单位B
                .setMaxPixel(800)//压缩后长或宽不超过的最大像素,单位px
                .create();

        takePhoto.onEnableCompress(config, true);
    }


    /**
     * 裁剪
     *
     * @return
     */
    private CropOptions getCropOptions() {
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setOutputX(800).setOutputY(800);//裁剪框宽高
        builder.setWithOwnCrop(true);
        return builder.create();
    }

    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        super.onActivityReenter(resultCode, data);
    }


    @Override
    public void takeSuccess(TResult result) {

        Log.i("1211", "takeSuccess：" + result.getImage().getCompressPath());
        TImage image = result.getImage();
        Glide.with(this).load(image.getCompressPath()).into(my_head);

        upLoudFile(image);

    }

    private void upLoudFile(TImage image) {
        String originalPath = image.getCompressPath();
        File file = new File(originalPath);
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Builder builder = new MultipartBody.Builder();


        String fileName = UUID.randomUUID().toString() + file.getName();
        LogUtil.e("上传头像名为0：", fileName);
        fileName = fileName.substring(fileName.length() - 4, fileName.length());
        LogUtil.e("上传头像名为1：", fileName);
        fileName = userName+ fileName;

        LogUtil.e("上传头像名为：", fileName);

        builder.addFormDataPart("file1", fileName, imageBody);//1.字段名 多张图片为file1-9 ;2.image的资源名；3.image资源文件
        List<MultipartBody.Part> parts = builder.build().parts();
        upHeadPresenter.upHead(parts);

    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i(TAG, getResources().getString(R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public void getSelectServer(upHead s) {
        LogUtil.e("000", s.getStatus() + "<>");
    }
}
